package com.wolfking.demo.nio.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.StandardCharsets;

public class TimeClient {

    public void connet(String host, int port) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast(new TimeClientHandler());
                        }
                    });
            ChannelFuture sync = b.connect(host, port).sync();
            final byte[] bytes = "Query Time ORDER".getBytes(StandardCharsets.UTF_8);
            ByteBuf message = Unpooled.copiedBuffer(bytes);
            sync.channel().writeAndFlush(message);
            sync.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    private static class TimeClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf byteBuf = (ByteBuf) msg;
            byte[] req = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(req);
            String message = new String(req, StandardCharsets.UTF_8);
            System.out.println(" server message is :" + message);
            String respone = System.currentTimeMillis() + "";
            ByteBuf wr = Unpooled.copiedBuffer(respone.getBytes(StandardCharsets.UTF_8));
            ctx.write(wr);
        }
    }

    public static void main(String[] args) throws Exception {
        new TimeClient().connet("127.0.0.1", 9999);
    }
}
